package base.engine;

import base.Start;

public class UpdateThread implements Runnable
{
	/**Should RenderHandler update screen*/
	public static boolean shouldScreenUpdate = false;

	/**Maximum updates per tick*/
	private static final double UPDATES_PER_TICK = 1000000000D / Start.FPS_MAX;

	/**Time difference between each tick; useful for interpolation*/
	private double timeDelta = 0D;
	/**Previous tick time*/
	private long timePrev = 0;
	/**First tick time*/
	private long timeInit = 0;

	@Override
	public void run()
	{
		this.timePrev = System.currentTimeMillis();
		this.timeInit = System.nanoTime();

		while(Start.isRunning())
		{
			long curTime = System.nanoTime();
			this.timeDelta += (curTime - this.timeInit) / UPDATES_PER_TICK;
			this.timeInit = curTime;

			//Update cycle
			while(this.timeDelta >= 1)
			{
				this.timeDelta--;
				if (!Start.expireManager)
				{
					updateApplication();
				}
				shouldScreenUpdate = true;
			}

			//If >= 1 second
			if (System.currentTimeMillis() - this.timePrev >= 1000)
			{
				//Reset Timer
				this.timePrev += 1000;
			}

			try
			{
				Thread.sleep(2);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}

	protected void updateApplication()
	{
		Start.worldManager.update();
		Start.inputManager.update();
	}
}
